/*
* Copyright 2005-2008 Pulse Technologies. Tutti i diritti riservati.
*/
package org.obsidianrad.server.services.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken;

/**
 * 
 * @author Eligio Colutta
 * @version $Rev: 4 $
 * @lastautorcommit $Author: eliosh $
 * @lastdatecommit $Date: 2009-10-31 12:37:28 +0100(sab, 31 ott 2009) $
 */
public class UserProxyImpl implements UserProxy {

	private AuthenticationManager authManager; 
	
	@Override
	public ObsidianUser getCurrentUser() {
		ObsidianUser ou = null;
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth==null){
			return null;
		} else if(!auth.isAuthenticated()){
			return null;
		} else if (auth instanceof AnonymousAuthenticationToken) {
			return null;
		}
		
		GrantedAuthority[] authorities = auth.getAuthorities();
		List<String> roleArray = new ArrayList<String>();
		for(GrantedAuthority au : authorities){
			roleArray.add(au.getAuthority());
		}
		ou = new ObsidianUser();
		ou.setName(auth.getName());
		String[] roles = new String[roleArray.size()];
		ou.setRoles(roleArray.toArray(roles));
//		ou.setPreferences((Map<String, Object>) auth.getDetails());

		// TODO recuperare la lista dei contesti e il contesto attivo
		
		return ou;
	}

	public ObsidianUser authenticateUser(String user, String password) {
//		SecurityContextHolder.getContext().setAuthentication(null);
//		Authentication validUser = authManager.authenticate(new UsernamePasswordAuthenticationToken(user, password));		
//		if( validUser!=null && validUser.isAuthenticated() ){
//			SecurityContextHolder.getContext().setAuthentication(validUser);
//			return getCurrentUser();
//		}else{
//			return null;
//		}
		return null;
	}
	
	public AuthenticationManager getAuthManager() {
		return authManager;
	}

	public void setAuthManager(AuthenticationManager authManager) {
		this.authManager = authManager;
	}

}
